<?php
namespace app\controllers\api\account;

use fate\http\Request;
use app\models\User;
use app\libs\LibUser;
use app\libs\Util;
use app\services\VerifyCodeService;

class LoginController extends \fate\web\PureController {
    public function run() {
        $req = Request::getInstance();

        $account = Util::plainText($req->getParameter('account'));
        $pwd = $req->getParameter('password');
        $verifyCode = Util::plainText($req->getParameter('verify_code'));
        $isEmail = Util::plainText($req->getParameter('is_email'));

        if(!$account || !$pwd) {
            $this->ajaxReturn(null, 300002);
            exit;
        }

        $service = new VerifyCodeService();
        if(!$service->validateVerifyCode($verifyCode)) {
            $this->ajaxReturn(null, 100004);
            exit;
        }

        $user = new User();
        $where = $isEmail === '1' ? "email='{$account}'" : "user_name='{$account}'";
        $ret = $user->getOneByCondition('id, password, status', $where);

        if(null === $ret) {
            $this->ajaxReturn(null, 100008);
            exit;
        }

        if('1' !== $ret['status']) {
            $this->ajaxReturn(null, 100010);
            exit;
        }

        if(md5($pwd) === $ret['password']) {
            unset($ret['password']);

            LibUser::login($ret['id']);

            $this->ajaxReturn([
                'str_uid' => LibUser::encodeId($ret['id'])
            ]);
            exit;
        }

        $this->ajaxReturn(null, 100007);
    }
}

